import React,{useState,useRef,useLayoutEffect} from 'react'
import ReactDOM from 'react-dom'

export default function KeepAlive(props) {

  const [targetElement] = useState(()=>document.createElement('div')) //创建一个div容器
  const containerRef = useRef()

  useLayoutEffect(() => {
    const {active}=props
    if(active){
      containerRef.current.appendChild(targetElement)
    }else{
      try{
        containerRef.current.removeChild(targetElement)
      }catch(err){console.log(err)}
    }

  }, [props,targetElement])

  return (
    <>
      <div ref={containerRef}>
        {ReactDOM.createPortal(props.children,targetElement)}
      </div>
    </>
  )
}
